package com.msb.api.controller;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.msb.api.enums.SmsCodeEnum;
import com.msb.api.filter.CheckFilterContext;
import com.msb.api.form.SingSendForm;
import com.msb.api.util.R;
import com.msb.api.vo.ResultVo;
import com.msb.common.constart.RabbitMQConstants;
import com.msb.common.model.StandardSubmit;
import com.msb.common.util.SnowFlakeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @Author: lmf
 * @Create: 2025/3/7 10:06
 * @module 短信服务
 */
@RestController
@RequestMapping("/sms")
@Slf4j
@RefreshScope
public class SmsController {
    @Resource
    private SnowFlakeUtil snowFlakeUtil;
    @Resource
    private CheckFilterContext checkFilterContext;

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送单条短信
     */
    @PostMapping(value = "/single_send", produces = "application/json")
    public ResultVo singleSend(@Validated @RequestBody() SingSendForm singSendForm, BindingResult bindingResult,
                               HttpServletRequest request) {
        // 校验参数
        if (bindingResult.hasErrors()) {
            String message = Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage();
            log.info("参数校验失败：{}", message);
            return R.error(SmsCodeEnum.PARAMETER_ERROR.getCode(), message);
        }

        // ===========获取ip=============

        String ip = getRealIp(request);

        // ===========构建StandardSubmit=============
        final StandardSubmit standardSubmit = new StandardSubmit();
        standardSubmit.setRealIp(ip);
        standardSubmit.setSendTime(LocalDateTime.now());
        BeanUtils.copyProperties(singSendForm, standardSubmit);


        // ===========调用策略模块进行验证=============
        checkFilterContext.check(standardSubmit);

        // ===========基于雪花算法生成唯一id=============
        standardSubmit.setSequenceId(snowFlakeUtil.nextId());


        // ===========发送到mq，交给策略模块处理=============
        rabbitTemplate.convertAndSend(RabbitMQConstants.SMS_PRE_SEND, standardSubmit,
                new CorrelationData(standardSubmit.getSequenceId().toString()));

        // ===========没有问题返回成功=============

        return R.ok();
    }


    @Value("${headers:x-forwarded-for,Proxy-Client-IP,WL-Proxy-Client-IP,HTTP_CLIENT_IP,HTTP_X_FORWARDED_FOR}")
    private String headers;

    /**
     * 获取ip地址
     */
    private String getRealIp(HttpServletRequest request) {
        String ip;
        String UNKNOWN = "unknown";
        String X_FORWARDED_FOR = "x-forwarded-for";

        for (String header : headers.split(",")) {
            ip = request.getHeader(header);

            if (StringUtils.isNotEmpty(ip) && !UNKNOWN.equalsIgnoreCase(ip)) {
                // 多次转发只获取第一次的ip
                if (X_FORWARDED_FOR.equalsIgnoreCase(header)) {
                    final String[] i = ip.split(",");
                    if (i.length > 0) {
                        ip = i[0];
                    }
                }
                return ip;
            }
        }
        // 没有获取到的话，就获取本地ip
        return request.getRemoteAddr();
    }
}
